import { Inject, Provide } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { Utils } from "../utils";
import { BblFeed } from "../entity/feed.entity";
import { FeedCreateDto, FeedPageQueryDto, FeedDto } from "../dto/feed.dto";

@Provide()
export class FeedService {
  @Inject()
  utils: Utils;

  /**
   * 附件驱动模型
   */
  @InjectEntityModel(BblFeed)
  feedModel: Repository<BblFeed>;

  async add_feed(dto: FeedCreateDto) {
    const feed = FeedDto.toFeed(dto);
    feed.feedId = this.utils.uuid();
    const result = this.feedModel.save(feed);
    return this.utils.service.success(result);
  }

  async resolve_feed(feedId: string, resolveSchema: string) {
    const feed = await this.feedModel.findOne({
      where: {
        feedId
      }
    });
    if (!feed) {
      return this.utils.service.fail("咨询不存在");
    } else {
      feed.state = 1;
      feed.resolveSchema = resolveSchema;
      const result = await this.feedModel.save(feed);
      return this.utils.service.success(result);
    }
  }

  async get_feed_page_list(dto: FeedPageQueryDto) {
    const builder = this.feedModel
      .createQueryBuilder("feed")
      .where("1=1")
      .orderBy("feed.createAt", "DESC");

    if (dto.state) {
      builder.andWhere("feed.state=:state", {
        state: dto.state
      });
    }

    const total = await builder.getCount();

    builder.skip((dto.current - 1) * dto.pageSize);
    builder.take(dto.pageSize);

    const result = await builder.getMany();

    const records = result.map((d) => new FeedDto(d));

    return this.utils.service.success({
      total,
      records,
      current: Number(dto.current),
      pageSize: Number(dto.pageSize)
    });
  }
}
